package net.bingosoft.common.struts.tags;

import java.util.Enumeration;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.struts.taglib.TagUtils;

/**
 * 2007-8-24 上午09:50:59
 * Author:yangdongyu(yangdy@bingosoft.net)
 * ReadMe:查看相关属性的标签
 * ChangeLog:
 */
public class DumpTag extends TagSupport {

	private static final long serialVersionUID = 1L;

	private int scope;
	private String name;
	private String property;
	private String scopeName;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getProperty() {
		return property;
	}

	public void setProperty(String property) {
		this.property = property;
	}

	public DumpTag() {
	}

	public void setScope(String sc) throws JspException {
		if (sc.equalsIgnoreCase("session"))
			scope = 3;
		else if (sc.equalsIgnoreCase("request"))
			scope = 2;
		else if (sc.equalsIgnoreCase("application"))
			scope = 4;
		else if (sc.equalsIgnoreCase("page"))
			scope = 1;
		else
			throw new JspException(
					"Scope must be page, request, session or application.");
		this.scopeName = sc;
	}

	public int doEndTag() throws JspException {
		try {
			if(name == null && property == null){
				Enumeration names = pageContext.getAttributeNamesInScope(scope);
				pageContext.getOut().write("<dl>");
				Object value;
				for (; names.hasMoreElements(); pageContext.getOut().write("<dd><code>" + value + "</code></dd>")) {
					String name = (String) names.nextElement();
					value = pageContext.getAttribute(name, scope);
					pageContext.getOut().write("<dt><code>" + name + "</code></dt>");
				}

				pageContext.getOut().write("</dl>");
			}else{
				Object obj = TagUtils.getInstance().lookup(pageContext, name, property, scopeName);
				pageContext.getOut().write("<dl><dt><code>" + obj + "</code></dt></dl>");
			}
		} catch (Exception e) {
			throw new JspException("Exception: " + e.getMessage());
		}
		return EVAL_PAGE;
	}
}
